package com.online.usermanagesystem.service.impl;

import com.online.usermanagesystem.entity.Account;
import com.online.usermanagesystem.entity.Session;
import com.online.usermanagesystem.service.AccountManageService;
import com.online.usermanagesystem.service.SessionManageService;
import com.online.usermanagesystem.utils.ConcurrentLRUMap;
import com.online.usermanagesystem.utils.ResultUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * 会话管理的处理类
 *
 * @create 2018-04-24 10:35
 */
@Component
public class SessionManageServiceImpl implements SessionManageService {

    @Autowired
    private AccountManageService accountManageService;

    private ConcurrentLRUMap<String, Session> LRUMap = new ConcurrentLRUMap(65535);

    private long expire_msec = 3 * 60 * 1000;
    private long expire_sec = 3 * 60;

    @Override
    public Object login(String name, String password) {
        if ((null == name) || (null == password)) {
            return ResultUtil.BAD_REQUEST;
        }

        Object obj = accountManageService.auth(name, password);
        if (false == ResultUtil.isSuccess(obj)) {
            return obj;
        }

        String token = UUID.randomUUID().toString().replace("-", "");
        long time = System.currentTimeMillis();

        Account account = (Account) obj;
        Map map = new HashMap();
        map.put("id", account.getId());
        map.put("nickname", account.getNickname());
        map.put("avatar", account.getAvatar());
        map.put("token", token);
        map.put("timestamp", time);
        map.put("expire_sec", expire_sec);

        LRUMap.put(token, new Session(account.getId(), time));
        return map;
    }

    @Override
    public Object logout(String token) {
        if (null == token) {
            return ResultUtil.BAD_REQUEST;
        }

        LRUMap.remove(token);
        return ResultUtil.OK;
    }

    @Override
    public Object find(String token) {
        if (null == token) {
            return ResultUtil.BAD_REQUEST;
        }

        Session data = LRUMap.get(token);
        if (null == data) {
            return ResultUtil.NOT_FOUND;
        }

        long currentTime = System.currentTimeMillis();
        if (currentTime > data.getTimestamp() + expire_msec) {
            LRUMap.remove(token);
            return ResultUtil.NOT_FOUND;
        }

        data.setTimestamp(currentTime);
        return data;
    }
}
